/*
 * Copyright 2016 Kejun Xia
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shipdream.lib.ohos.mvc.view.viewpager;


import com.shipdream.lib.ohos.mvc.FragmentTransaction;
import com.shipdream.lib.ohos.mvc.MvcFragment;
import com.shipdream.lib.ohos.mvc.Reason;
import com.shipdream.lib.ohos.mvc.ResourceTable;
import com.shipdream.lib.ohos.mvc.view.help.LifeCycleMonitor;
import com.shipdream.lib.ohos.mvc.view.viewpager.controller.FirstFragmentController;
import com.shipdream.lib.poke.util.ReflectUtils;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.utils.PacMap;

import javax.inject.Inject;

public class ViewPagerHomeFragment extends MvcFragment<FirstFragmentController> {
    PageSlider viewPager;

    private PagerAdapter pagerAdapter;

    @Inject
    private LifeCycleMonitor lifeCycleMonitor;

    @Override
    protected Class<FirstFragmentController> getControllerClass() {
        return FirstFragmentController.class;
    }

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_fragment_view_pager_home;
    }

    @Override
    public void onViewReady(Component view, PacMap savedInstanceState, Reason reason) {
        lifeCycleMonitor.onCreateView(view, savedInstanceState);
        lifeCycleMonitor.onViewCreated(view, savedInstanceState);
        super.onViewReady(view, savedInstanceState, reason);
        lifeCycleMonitor.onViewReady(view, savedInstanceState, reason);

        viewPager = (PageSlider) view.findComponentById(ResourceTable.Id_viewpager);
        pagerAdapter = new PagerAdapter();
        viewPager.setProvider(pagerAdapter);
        viewPager.addPageChangedListener(pagerAdapter);
        getFractionAbility().getUITaskDispatcher().delayDispatch(() -> pagerAdapter.onPageChosen(0), 200);

    }

    @Override
    public void onCreate(PacMap savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifeCycleMonitor.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        lifeCycleMonitor.onResume();
    }

    @Override
    protected void onReturnForeground() {
        super.onReturnForeground();
        lifeCycleMonitor.onReturnForeground();
    }

    @Override
    protected void onPushToBackStack() {
        super.onPushToBackStack();
        lifeCycleMonitor.onPushToBackStack();
    }

    @Override
    protected void onPopAway() {
        super.onPopAway();
        lifeCycleMonitor.onPopAway();
    }

    @Override
    protected void onPoppedOutToFront() {
        super.onPoppedOutToFront();
        lifeCycleMonitor.onPoppedOutToFront();
    }

    @Override
    protected void onOrientationChanged(int lastOrientation, int currentOrientation) {
        super.onOrientationChanged(lastOrientation, currentOrientation);
        lifeCycleMonitor.onOrientationChanged(lastOrientation, currentOrientation);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        lifeCycleMonitor.onDestroyView();
    }

    @Override
    public void onDestroy() {
        lifeCycleMonitor.onDestroy();
        super.onDestroy();
    }

    @Override
    public void update() {

    }

    private class PagerAdapter extends PageSliderProvider implements PageSlider.PageChangedListener {


        private static final int BASE_ITEM_ID = 1000000;

        private boolean needUpdateText;

        private Class<? extends MvcFragment>[] tabs = new Class[]{
                TabFragmentA.class,
                TabFragmentB.class,
                TabFragmentC.class
        };

        private boolean[] adds = new boolean[]{false, false, false};

        @Override
        public int getCount() {
            return tabs.length;
        }

        private MvcFragment getItem(int position) {
            Class<? extends MvcFragment> fragmentClass = tabs[position];
            final MvcFragment currentFragment;
            try {
                currentFragment = (MvcFragment) new ReflectUtils.newObjectByType(fragmentClass).newInstance();
            } catch (Exception e) {
                return null;
            }
            return currentFragment;
        }


        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int position) {
            Component component = LayoutScatter.getInstance(getFractionAbility()).parse(ResourceTable.Layout_fragment_view_pager_root, null, false);
            component.setId(position + BASE_ITEM_ID);
            componentContainer.addComponent(component);
            return component;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object object) {
            componentContainer.removeComponent((Component) object);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object object) {
            return component == object;
        }


        @Override
        public void onPageSliding(int ii, float vv, int i1) {

        }

        @Override
        public void onPageSlideStateChanged(int ii) {

        }

        @Override
        public void onPageChosen(int position) {
            if (!adds[position]) {
                MvcFragment item = getItem(position);
                FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
                fragmentTransaction.add(position + BASE_ITEM_ID, item, item.getClass().getSimpleName());
                fragmentTransaction.commit();
                adds[position] = true;
            } else {
                if (position == 0 && needUpdateText) {
                    Fraction fragmentA = getChildFragmentManager().findFragmentByTag("TabFragmentA");
                    if (fragmentA != null) {
                        TabFragmentA tabFragmentA = (TabFragmentA) fragmentA;
                        tabFragmentA.setText();
                    }
                }
            }
            if (position == 2) {
                needUpdateText = true;
            }
        }
    }
}
